<script setup>
import reserveApi from '@/api/reserveApi';
import { reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import doctorSchedulesApi from '@/api/doctorSchedulesApi';
import doctorsApi from "@/api/doctorsApi";
import patientsApi from "@/api/patient";
import {Refresh, Search} from "@element-plus/icons-vue";
import * as XLSX from "xlsx";

const reserves = ref([]);

// 分页信息
const pageInfo = reactive({
    page: 1,
    limit: 10,
    total: 0,
})

// 添加日期范围临时变量
const dateRangeValue = ref(null);

// 获取预约列表
loadReserves();

// 页码和页面大小更新
function loadReserves() {
    reserveApi.search(pageInfo).then(result => {
        reserves.value = result.data.records;
        pageInfo.total = result.data.total;
    });
}

// 添加的相关操作
const addVisible = ref(false);
const addReserve = ref({roles:[]});
function showAdd() {
    addVisible.value = true;    // 显示添加窗口
}

function handleAdd(){
    reserveApi.add(addReserve.value).then(result=>{
        if (result.code == 200) {
            ElMessage({ message: '预约创建成功！', type: 'success' })
            addVisible.value = false;
            addReserve.value = {};
        } else {
            ElMessage.error(result.data);
        }
        // 刷新表格数据
        loadReserves();
    });
}

// 编辑的操作
const editVisible = ref(false);
const editReserve = ref({});


// 修改 showEdit 方法，添加状态检查
function showEdit(row) {
  // 检查预约状态，如果已取消则不允許編輯
  if (row.status == 0) {
    ElMessage.warning('已取消的预约无法编辑');
    return;
  }

  editVisible.value = true;
  editReserve.value = JSON.parse(JSON.stringify(row));   // 深拷贝
  editReserve.value.password = "";
}

function handleEdit(){
    reserveApi.edit(editReserve.value).then(result=>{
        if (result.code == 200) {
            ElMessage({ message: '编辑预约成功！', type: 'success' })
            editVisible.value = false;
        } else {
            ElMessage.error(result.data);
        }
        // 刷新表格数据
        loadReserves();
    });
}
function handleCancel(row){
    ElMessageBox.confirm(
        '亲，确定要取消当前预约么?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '不了',
            type: 'warning',
        }
    ).then(()=>{
        // 确定
        editReserve.value = JSON.parse(JSON.stringify(row));   // 深拷贝
        editReserve.value.password = "";
        editReserve.value.status = 0;
        reserveApi.remove(editReserve.value).then(result=>{
            if (result.code == 200) {
                ElMessage({ message: '取消预约成功！', type: 'success' })
            } else {
                ElMessage.error(result.msg);
            }
            // 刷新表格数据
            loadReserves();
        });
    });
}

// 解析类型显示
function fmtStatus(row, column, cellValue, index) {
    return ['已取消','已预约', '已完成', '未到'][row.status];
}

// 下拉列表
const doctors = ref([]);
const patients = ref([]);
const doctorSchedules = ref([]);

loadDoctorSchedules();
loadDoctors();
loadPatients();
//查询全部病人信息
function loadPatients(){
    patientsApi.search().then(result => {
    patients.value = result.data;
    });
}
// 页码和页面大小更新
function loadDoctorSchedules() {
    doctorSchedulesApi.search().then(result => {
      // console.log(result.data)
      doctorSchedules.value = result.data;
    });
}
function loadDoctors() {
  doctorsApi.getAll().then(result => {
    doctors.value = result.data;
    });
}

function onSearch(){
    pageInfo.page = 1;
    loadReserves();
}
// 添加时间范围选择处理函数
function handleDateRangeChange(value) {
  if (value && value.length === 2) {
    pageInfo.startTime = value[0];
    pageInfo.endTime = value[1];
  } else {
    pageInfo.startTime = null;
    pageInfo.endTime = null;
    dateRangeValue.value = null;
  }
}

// 根据状态返回不同的样式类
function getStatusClass(row) {
  // 0: 已取消, 1: 已预约, 2: 已完成, 3: 未到
  const statusClasses = ['status-cancelled', 'status-reserved', 'status-completed', 'status-absent'];
  return statusClasses[row.status] || '';
}
// 重置搜索条件
function resetSearch() {
  // 清空搜索条件
  pageInfo.patientId = null;
  pageInfo.scheduleId = null;
  pageInfo.startTime = null;
  pageInfo.endTime = null;
  dateRangeValue.value = null;

  // 重置页码
  pageInfo.page = 1;
  loadReserves();
}


// 导出Excel功能
function exportToExcel() {
  // 准备导出数据
  const exportData = reserves.value.map(item => ({
    'ID': item.id,
    '患者': item.patient?.name || '',
    '活动名称': item.doctorSchedules?.name || '',
    '医生': item.doctor?.name || '',
    '义诊开始时间': item.doctorSchedules?.startTime || '',
    '时长': item.doctorSchedules?.longTime || '',
    '预约时间': item.reserveTime || '',
    '评分': item.score || '',
    '评语': item.comment || '',
    '评价时间': item.commentTime || '',
    '状态': fmtStatus(item, null, null, null)
  }));

  // 创建工作簿
  const wb = XLSX.utils.book_new();

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(exportData);

  // 设置列宽
  ws['!cols'] = [
    { wch: 10 }, // ID
    { wch: 15 }, // 患者
    { wch: 20 }, // 活动名称
    { wch: 15 }, // 医生
    { wch: 20 }, // 义诊开始时间
    { wch: 10 }, // 时长
    { wch: 20 }, // 预约时间
    { wch: 10 }, // 评分
    { wch: 20 }, // 评语
    { wch: 20 }, // 评价时间
    { wch: 15 }  // 状态
  ];

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '预约信息');

  // 导出Excel文件
  XLSX.writeFile(wb, '预约信息.xlsx');
}
</script>

<template>
    <div class="content">
        <el-form :model="pageInfo" :inline="true">
            <el-form-item label="患者" :label-width="60">
                <el-select
                    v-model="pageInfo.patientId"
                    filterable
                    placeholder="请选择患者"
                    style="width: 240px"
                    clearable
                >
                    <el-option
                        v-for="item in patients"
                        :key="item.id"
                        :label="item.name + '-' + item.phone"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="义诊活动" :label-width="80">
                <el-select
                    v-model="pageInfo.scheduleId"
                    filterable
                    placeholder="请选择活动"
                    style="width: 240px"
                    clearable
                >
                    <el-option
                        v-for="item in doctorSchedules"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
          <el-form-item label="预约时间" :label-width="80">
            <el-date-picker
                v-model="dateRangeValue"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 240px"
                clearable
                @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch" class="search-button">
              <el-icon><Search /></el-icon>
              <span>搜索</span>
            </el-button>
            <el-button @click="resetSearch" class="reset-button">
              <el-icon><Refresh /></el-icon>
              <span>重置</span>
            </el-button>

          </el-form-item>
        </el-form>
        <div class="bar">
            <el-button type="success" @click="showAdd" >添加预约</el-button>
          <el-button type="primary" @click="exportToExcel">导出当前页</el-button>
        </div>
        <el-table :data="reserves" :stripe="true" :border="true" style="width: 100%">
            <el-table-column prop="id" label="ID" width="60" fixed />
            <el-table-column prop="patient.name" label="患者"  width="100"  fixed/>
            <el-table-column prop="doctorSchedules.name" label="活动名称" width="160" fixed/>
            <el-table-column prop="doctor.name" label="医生" />
            <el-table-column prop="doctorSchedules.startTime" label="义诊开始时间" width="180" />
            <el-table-column prop="doctorSchedules.longTime" label="时长"  width="80"/>
            <el-table-column prop="reserveTime" label="预约时间" width="180" />
            <el-table-column prop="score" label="评分"  width="60"/>
            <el-table-column prop="comment" label="评语" width="180" />
            <el-table-column prop="commentTime" label="评价时间" width="180" />
          <el-table-column prop="status" label="状态" width="100" :formatter="fmtStatus" fixed="right">
            <template #default="scope">
                <span :class="['status-badge', getStatusClass(scope.row)]">
                    {{ fmtStatus(scope.row, null, null, null) }}
                </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button
                  size="small"
                  type="warning"
                  @click="handleCancel(scope.row)"
                  :disabled="scope.row.status === 0"
              >
                取消预订
              </el-button>
              <el-button
                  size="small"
                  type="success"
                  @click="showEdit(scope.row)"
                  :disabled="scope.row.status === 0"
              >
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
            :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
            layout="total, sizes, prev, pager, next, jumper" @change="loadReserves" />
    </div>

    <!-- 添加的弹窗 -->
    <el-dialog v-model="addVisible" title="创建新预约" width="500">
        <el-form :model="addReserve">
            <el-form-item label="患者" :label-width="80">
                <el-select
                    v-model="addReserve.patientId"
                    filterable
                    placeholder="请选择患者"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in patients"
                    :key="item.id"
                    :label="item.name + '-' + item.phone"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="义诊活动" :label-width="80">
                <el-select
                    v-model="addReserve.scheduleId"
                    filterable
                    placeholder="请选择活动"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in doctorSchedules"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">
                    立即预约
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑的弹窗 -->
    <el-dialog v-model="editVisible" title="编辑预约" width="500">
        <el-form :model="editReserve">
            <el-form-item label="患者" :label-width="60">
                <el-select
                    v-model="editReserve.patientId"
                    filterable
                    placeholder="请选择患者"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in patients"
                    :key="item.id"
                    :label="item.name + '-' + item.phone"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="活动" :label-width="60">
                <el-select
                    v-model="editReserve.scheduleId"
                    filterable
                    placeholder="请选择义诊活动"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in doctorSchedules"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEdit">
                    修改预约
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style scoped>/* 状态标签样式 */
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  white-space: nowrap;
}

/* 已取消状态 - 灰色 */
.status-cancelled {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #d3d4d6;
}

/* 已预约状态 - 蓝色 */
.status-reserved {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

/* 已完成状态 - 绿色 */
.status-completed {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

/* 未到状态 - 红色 */
.status-absent {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}
/* 搜索按钮样式 */
.search-button {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  font-size: 14px;
}

.reset-button {
  margin-left: 10px;
  padding: 8px 16px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-button span {
    display: none;
  }

  .search-button .el-icon {
    margin-right: 0;
  }

  .search-button {
    padding: 8px 12px;
  }
}

</style>